package by.grsu.mikhailava.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import by.grsu.mikhailava.entity.Subject;
import by.grsu.mikhailava.table.SubjectTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

public class SubjectDao extends AbstractDao<SubjectTable, Subject>{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -8668331317556125267L;

	public SubjectDao(String rootFolderPath) {
		super(rootFolderPath);
	}
	
	public Subject searchBySubjectName(String desiredSubject) {
		final SubjectTable subjectTable = deserializeFromXml();
		Subject subject = new Subject();
		for (final Subject s : subjectTable.getRows()) {
			if (s.getSubjectName().equals(desiredSubject)) {
				subject = s;
				break;
			}
		}
		return subject;
	}

	@Override
	public void saveNew(final Subject newSubject) {
		newSubject.setId(getNextId());
		final SubjectTable subjectTable = deserializeFromXml();
		subjectTable.getRows().add(newSubject);
		serializeToXml(subjectTable);
	}

	@Override
	public void update(final Subject entity) {
		final SubjectTable subjectTable = deserializeFromXml();
		for (final Subject s : subjectTable.getRows()) {
			if (s.getId().equals(entity.getId())) {
				s.setSubjectName(entity.getSubjectName());
				break;
			}
		}
		serializeToXml(subjectTable);

	}

	@Override
	public Subject get(Serializable id) {
		final SubjectTable subjectTable = deserializeFromXml();
		for (final Subject s : subjectTable.getRows()) {
			if (s.getId().equals(id)) {
				return s;
			}
		}

		return null;
	}

	@Override
	public List<Subject> getAll() {
		final SubjectTable subjectTable = deserializeFromXml();
		return subjectTable.getRows();
	}
	public List<Long> getAllID() {
		final SubjectTable subjectTable = deserializeFromXml();
		List<Long> listID= new ArrayList<Long>();
		for (Subject s : subjectTable.getRows()) {
			listID.add(s.getId());
		}
		return listID;
	}


	@Override
	public void delete(Serializable id) {
		final SubjectTable subjectTable = deserializeFromXml();
		Subject subjectToDelete = null;
		for (final Subject s : subjectTable.getRows()) {
			if (s.getId().equals(id)) {
				subjectToDelete = s;
				break;
			}
		}
		subjectTable.getRows().remove(subjectToDelete);
		serializeToXml(subjectTable);
	}

	@Override
	protected Class<SubjectTable> getTableClass() {
		return SubjectTable.class;
	}
	
	

}
